<?php

namespace app\beautiful\controller\admin\partner\giftbag;

use app\beautiful\model\CouponModel;
use app\beautiful\model\giftbag\GiftbagDetailModel;
use app\beautiful\model\GiftbagModel;

use app\BaseController;

use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;
use app\common\logic\DataLogic;
use think\facade\Db;
use think\Model;


class Giftbag extends BaseController{

    protected $name='礼包';



    public function index()

    {

        $search=$this->request->param('search');

        $where=[

            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0]

        ];
        if($search){
            $where[]=['name','like','%'.$search.'%'];
        }
        $giftbag_model= new GiftbagModel();

        $giftbag_model = $giftbag_model->withCount(['GiftbagDetail'=>function($query){

            $query->where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0]

            ]);

        }]);

        $order=['update_time'=>'desc','add_time'=>'desc'];

        $field="giftbag_id,name,add_time";

        $append=[];

        $return = DataLogic::getDataList($giftbag_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }



    public function show()

    {

        $giftbag_id=$this->request->param('giftbag_id/d',0);

        if($giftbag_id==0){

            return $this->success([]);

        }
        $giftbag= GiftbagModel::with(['GiftbagDetail'=>function($query){
                    $query->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
                }])->where(['shop_id'=>$this->request->shopId,'giftbag_id'=>$giftbag_id,'is_delete'=>0])->find();

        if(null === $giftbag){

            return $this->error($this->name.'不存在');

        }
        $detail = $this->detail($giftbag->GiftbagDetail);


        $giftbag['selected_detail'] = [
            'data'=>$detail['data'],
            'cate_count'=>count($detail['goods_cate'])+count($detail['coupon_cate']),
            'num'=>$detail['num'],
        ];

        return $this->success(['detail'=>$giftbag]);

    }

    protected function detail($giftbagDetail){
        $data = $goods_cate = $coupon_cate = [];
        $num = 0;
        foreach ($giftbagDetail as $k=>$v){
            if($v['goods_id']){
                $goods = GoodsModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'goods_id'=>$v['goods_id']])->find();
                $cate = GoodsCategoryModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1,'category_id'=>$v['category_id']])->find();
                if($goods){
                    $data[]=[
                        'giftbag_detail_id'=>$v['giftbag_detail_id'],
                        'cate_name'=>$cate?$cate->name:'',
                        'name'=>$goods['name'],
                        'num'=>$v['num'],
                        'type'=>'产品',
                        'detail'=>[
                            'name'=>$goods['name'],
                            'is_once_complete'=>$v['is_once_complete'],
                            'once_limit_num'=>$v['once_limit_num'],
                            'end_type'=>$v['end_type'],
                            'end_time_num'=>$v['end_time_num'],
                            'end_time_type'=>$v['end_time_type'],
                            'original_price'=>$goods['original_price']
                        ]
                    ];
                    $goods_cate [$v['category_id']] = $v['category_id'];
                }


            }
            if($v['coupon_id']){
                $coupon = CouponModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'coupon_id'=>$v['coupon_id']])->find();
                if($coupon){
                    $cate_name = '';
                    if($coupon['type']==1){
                        $cate_name = '普通券';
                    }
                    if($coupon['type']==2){
                        $cate_name = '新人券';
                    }
                    if($coupon['type']==3){
                        $cate_name = '会员券';
                    }
                    if($coupon['type']==4){
                        $cate_name = '邀请券';
                    }
                    if($coupon['type']==5){
                        $cate_name = '礼品券';
                    }
                    $data[]=[
                        'giftbag_detail_id'=>$v['giftbag_detail_id'],
                        'cate_name'=>$cate_name,
                        'name'=>$coupon['name'],
                        'num'=>$v['num'],
                        'type'=>'卡包',
                        'detail'=>[
                            'name'=>$coupon['name'],
                            'money_limit'=>$coupon['money_limit'],
                            'valid_bg_time'=>$coupon['valid_end_time'],
                            'valid_end_time'=>$coupon['valid_end_time'],
                            'coupon_money'=>$coupon['coupon_money']
                        ]
                    ];
                    $coupon_cate [$coupon['type']] = $coupon['type'];
                }

            }
            $num +=$v['num'];
        }
        $return['num'] = $num;
        $return['goods_cate'] = $goods_cate;
        $return['coupon_cate'] = $coupon_cate;
        $return['data'] = $data;

        return $return;
    }

    /*礼包详情删除*/
    public function detailDel(){
        $giftbag_id = $this->request->param('giftbag_id/d',0);
        $giftbag_detail_id = $this->request->param('giftbag_detail_id/d',0);
        if(null === $detail =GiftbagDetailModel::where(['shop_id'=>$this->request->shopId,'giftbag_id'=>$giftbag_id,'giftbag_detail_id'=>$giftbag_detail_id])->find()){
            return $this->error('详情不存在');
        }
        $detail->is_delete = 1;
        $detail->save();
        return $this->success('删除成功');
    }
    /*礼包详情设置信息*/
    public function detailSet(){
        $giftbag_id = $this->request->param('giftbag_id/d',0);
        $giftbag_detail_id = $this->request->param('giftbag_detail_id/d',0);
        if(null === $detail =GiftbagDetailModel::where(['shop_id'=>$this->request->shopId,'giftbag_id'=>$giftbag_id,'giftbag_detail_id'=>$giftbag_detail_id])->find()){
            return $this->error('详情不存在');
        }
        return $this->success($detail);
    }
    /*保存礼包详情设置*/
    public function detailSetSave(){
        $giftbag_id = $this->request->param('giftbag_id/d',0);
        $giftbag_detail_id = $this->request->param('giftbag_detail_id/d',0);
        $is_once_complete = $this->request->param('is_once_complete/d',1);
        $once_limit_num = $this->request->param('once_limit_num/d',0);
        $rules_type = $this->request->param('rules_type/d',1);
        $end_type = $this->request->param('end_type/d',0);
        $end_time_num = $this->request->param('end_time_num/d',0);
        $end_time_type = $this->request->param('end_time_type/d',1);

        if($is_once_complete<1 && $once_limit_num>10) return $this->error('单次限制使用数量不能超过10');

        if(null === $detail =GiftbagDetailModel::where(['shop_id'=>$this->request->shopId,'giftbag_id'=>$giftbag_id,'giftbag_detail_id'=>$giftbag_detail_id])->find()){
            return $this->error('详情不存在');
        }
        $detail->is_once_complete = $is_once_complete;
        $detail->once_limit_num = $once_limit_num;
        $detail->rules_type = $rules_type;
        $detail->end_type = $end_type;
        $detail->end_time_num = $end_time_num;
        $detail->end_time_type = $end_time_type;
        $detail->save();

        return $this->success('保存成功');
    }

    public function save()

    {

        $giftbag_id = $this->request->param('giftbag_id/d',0);
        $name = $this->request->param('name');
        $coupon_ids = $this->request->param('coupon_ids/a',[]);
        $goods_ids = $this->request->param('goods_ids/a',[]);
//
//        $coupon_ids[]=[
//            'giftbag_detail_id'=>1,
//            'coupon_id'=>6,
//            'num'=>1,
//            'is_once_complete'=>0,
//            'once_limit_num'=>1,
//            'rules_type'=>1,
//            'end_type'=>0,
//            'end_time_num'=>1,
//            'end_time_type'=>1,
//        ];
//        $goods_ids[]=[
//            'giftbag_detail_id'=>2,
//            'goods_id'=>223,
//            'num'=>1,
//            'is_once_complete'=>0,
//            'once_limit_num'=>1,
//            'rules_type'=>1,
//            'end_type'=>0,
//            'end_time_num'=>1,
//            'end_time_type'=>2,
//        ];

        if(empty($name) || mb_strlen($name)>40){

            return $this->error('名称必须填写且长度不能大于40');

        }


        //优惠券
        if(count($coupon_ids) < 1 && count($goods_ids) < 1){

           return $this->error('请选择礼包内容');

        }


        if($giftbag_id != 0){

            if(null === $giftbag = GiftbagModel::find($giftbag_id)){
                return $this->error($this->name.'不存在');
            }

            if($giftbag->shop_id != $this->request->shopId){
                return $this->error($this->name.'不存在');
            }

        }else{

            $giftbag = new GiftbagModel();

        }
        Db::startTrans();

        try{
            $giftbag->shop_id = $this->request->shopId;
            $giftbag->name = $name;
            $giftbag->update_time = $this->request->time();

            $giftbag->save();

            $giftbag_detail_data = array_merge($coupon_ids,$goods_ids);

            $old_giftbag_detail = GiftbagDetailModel::where([

                ['shop_id','=',$this->request->shopId],

                ['giftbag_id','=',$giftbag_id],

                ['is_delete','=',0]

            ])->select()->toArray();

            $update_detail_ids = array_column($giftbag_detail_data,'giftbag_detail_id') ?? []; $delete_giftbag_detail=[];

            $old_giftbag_detail_ids = array_column($old_giftbag_detail,'giftbag_detail_id') ?? [];

            foreach ($old_giftbag_detail as $k => $v){

                if(!in_array($v['giftbag_detail_id'],$update_detail_ids)){
                    $v['is_delete'] = 1;
                    $delete_giftbag_detail[] = $v;
                }

            }
            foreach ($giftbag_detail_data as $k => $v){

                $giftbag_detail_data[$k]['shop_id'] = $this->request->shopId;
                $giftbag_detail_data[$k]['giftbag_id'] = $giftbag->giftbag_id;

                if(isset($v['giftbag_detail_id'])){
                    if(!in_array($v['giftbag_detail_id'],$old_giftbag_detail_ids)) unset($giftbag_detail_data[$k]);

                }

            }

            $new_giftbag_detail_data = array_merge($giftbag_detail_data,$delete_giftbag_detail);

            $giftbag_detail_model = new GiftbagDetailModel();

            $giftbag_detail_model->saveAll($new_giftbag_detail_data);
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

        return $this->success('保存成功');

    }



    public function del()

    {

        $giftbag_id=$this->request->param('giftbag_id/d',0);

        if(null === $giftbag = GiftbagModel::find($giftbag_id)){

            return $this->error($this->name.'不存在');

        }


        if($giftbag->shop_id !=$this->request->shopId){

            return $this->error($this->name.'不存在');

        }
        Db::startTrans();

        try{
            $giftbag->is_delete = 1;
            $giftbag->save();

            GiftbagDetailModel::where(['shop_id'=>$this->request->shopId,'giftbag_id'=>$giftbag_id])->update(['is_delete'=>1]);
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('删除成功');

    }



}

